from flask import Flask, request, jsonify
import traceback



# 创建Flask应用
app = Flask(__name__)

# 定义图纸信息API接口
@app.route('/api/drawing_info', methods=['POST'])
def receive_drawing_information():
    try:
        # 1. 验证输入数据
        drawing_json = request.get_json()
        print(f'原始数据: {drawing_json}')
        if not drawing_json:
            return jsonify({"error": "请求体为空"}), 400
        print(f"📋 接收到图纸数据，数据条数: {len(drawing_json) if isinstance(drawing_json, list) else 1}")

        # 2. 数据格式适配器（兼容新旧接口格式）
        from utils.fun1 import convert_drawing_format
        drawing_json = convert_drawing_format(drawing_json)
        print(f"🔄 数据格式转换完成，转换后数据条数: {len(drawing_json) if isinstance(drawing_json, list) else 1}")

        # 3. 修补数据
        from utils.fun1 import fix_drawing_surfaces
        df_data = fix_drawing_surfaces(drawing_json)
        print(f"🔧 数据修补完成，处理后数据条数: {len(df_data)}")

        # 4. 
        from 正向分解2 import SmartProcessDesigner
        planer = SmartProcessDesigner()
        planer.read_final_inspection(df_data)
        planer.run()
        result = planer.new_graph['标准工序工步']
        print("✅ 正向分解完成，返回结果")
        return jsonify(result)
        
    except Exception as e:
        error_msg = f"处理失败: {str(e)}"
        print(f"❌ {error_msg}")
        traceback.print_exc()
        return jsonify({"error": error_msg}), 500

if __name__ == '__main__':
    # 绑定到所有网络接口，端口可自行修改
    app.run(host='0.0.0.0', port=5000, debug=True)
